package com.levi.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.levi.cache.UserCache;
import com.levi.common.AjaxResult;
import com.levi.domain.User;
import com.levi.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * @author shentong
 * @since 2022/3/11 9:51 PM
 */
@RestController
@RequestMapping("/user")
public class UserController {

	@Autowired
	private UserService userService;

	@PutMapping("edit/{id}")
	public AjaxResult edit(@PathVariable("id") String id, User user) {
		int i = Integer.parseInt(id);
		verify(i);
		user.setId(i);
		userService.updateById(user);
		return AjaxResult.ok();
	}

	@GetMapping("/byName")
	public User getUserByName(String username) {
		return UserCache.getUserByUserName(username);
	}

	@GetMapping("/byId")
	public User getUserById(Integer id) {
		return UserCache.getUserByUserId(id);
	}

	@GetMapping("/selectSql")
	public List<Map<String, Object>> selectUser() {
		EntityWrapper<User> ew = new EntityWrapper<>();
		ew.setSqlSelect("distinct c_username");
		List<Map<String, Object>> maps = userService.selectMaps(ew);
		return maps;
	}

	private User verify(Integer id) {
		User user = userService.selectById(id);
		if (user == null) {
			throw new NullPointerException("用户不存在！！");
		}
		return user;
	}

}
